const mysql = require('mysql2/promise');

async function addColumnsManually () {
  const connection = await mysql.createConnection({
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    timezone: '+08:00'
  });

  try {
    console.log('🔧 手动添加字段到map_areas表...\n');

    // 检查表结构
    console.log('📋 当前表结构:');
    const [columns] = await connection.execute('DESCRIBE map_areas');
    columns.forEach(col => {
      console.log(`  ${col.Field.padEnd(15)} | ${col.Type.padEnd(20)} | ${col.Null} | ${col.Key} | ${col.Default || 'NULL'}`);
    });

    // 添加parent_id字段
    console.log('\n➕ 添加parent_id字段...');
    try {
      await connection.execute(`
                ALTER TABLE \`map_areas\` 
                ADD COLUMN \`parent_id\` int(11) NULL COMMENT '父级区域ID' AFTER \`name\`
            `);
      console.log('✅ parent_id字段添加成功');
    } catch (error) {
      if (error.code === 'ER_DUP_FIELDNAME') {
        console.log('⚠️  parent_id字段已存在');
      } else {
        throw error;
      }
    }

    // 添加extension字段
    console.log('\n➕ 添加extension字段...');
    try {
      await connection.execute(`
                ALTER TABLE \`map_areas\` 
                ADD COLUMN \`extension\` varchar(50) NULL COMMENT '扩展字段(如等级信息)' AFTER \`parent_id\`
            `);
      console.log('✅ extension字段添加成功');
    } catch (error) {
      if (error.code === 'ER_DUP_FIELDNAME') {
        console.log('⚠️  extension字段已存在');
      } else {
        throw error;
      }
    }

    // 添加索引
    console.log('\n➕ 添加parent_id索引...');
    try {
      await connection.execute(`
                ALTER TABLE \`map_areas\` ADD INDEX \`idx_parent_id\` (\`parent_id\`)
            `);
      console.log('✅ parent_id索引添加成功');
    } catch (error) {
      if (error.code === 'ER_DUP_KEYNAME') {
        console.log('⚠️  parent_id索引已存在');
      } else {
        throw error;
      }
    }

    // 验证字段是否添加成功
    console.log('\n🔍 验证字段添加结果:');
    const [newColumns] = await connection.execute('DESCRIBE map_areas');
    newColumns.forEach(col => {
      console.log(`  ${col.Field.padEnd(15)} | ${col.Type.padEnd(20)} | ${col.Null} | ${col.Key} | ${col.Default || 'NULL'}`);
    });

    console.log('\n🎉 字段添加完成！');

  } catch (error) {
    console.error('❌ 添加字段失败:', error.message);
    if (error.code) {
      console.error('错误代码:', error.code);
    }
  } finally {
    await connection.end();
    console.log('\n🔌 数据库连接已关闭');
  }
}

addColumnsManually(); 